package s15.ch18.ex3;

public class MyThread implements Runnable {

	private String name;
	private Thread thread;
	private MyClass myClass;

	public MyThread(String name, MyClass myClass) {
		this.setName(name);
		this.setThread(new Thread(this, getName()));
		this.setMyClass(myClass);
	}

	public String getName() {
		return name;
	}

	public Thread getThread() {
		return thread;
	}

	@Override
	public void run() {

		try {
			getMyClass().wait();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		synchronized (getMyClass()) {

			System.out.println("I am " + getName());
			System.out.println(getName() + ", I get number " + getMyClass().getInteger());

			getMyClass().setInteger(getMyClass().getInteger() - 1);

			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(getName() + ", and now I get number " + getMyClass().getInteger());
			
		}
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setThread(Thread thread) {
		this.thread = thread;
	}

	public void start() {
		getThread().start();
	}

	public MyClass getMyClass() {
		return myClass;
	}

	public void setMyClass(MyClass myClass) {
		this.myClass = myClass;
	}

}
